import { API_URLS } from '../config'
import { MenuItem, Menu, MenuPageParams } from '../types/menu'
import { Response, PageData, defaultPageData } from '../types/common'
import { request } from '../utils/request'
import { ElMessage } from 'element-plus'

export const getMenuTree = async (): Promise<MenuItem[]> => {

  const response: Response<MenuItem[]> = await request(API_URLS.MENU_TREE, {
    method: 'GET'
  })
  if (response.code === 200) {
    return response.data
  }

  return []
} 

export const getMenuPage = async (params: MenuPageParams): Promise<PageData<Menu>> => {

  const response:Response<PageData<Menu>> = await request(API_URLS.MENU_PAGE, {
    method: 'POST',
    body: JSON.stringify(params)
  })

  if (response.code === 200) {
    return response.data
  }

  return defaultPageData
} 

export const deleteMenu = async (id: number | null): Promise<boolean> => {
  if (!id) return false
  const response:Response<boolean> = await request(`${API_URLS.MENU_BASE}/${id}`, {
    method: 'DELETE',
  })

  if (response.code === 200) {
    ElMessage.success('删除成功')
    return true
  } else {
    return false
  }
  
} 

export const addOrUpdateMenu = async (params: Menu, isAdd: boolean): Promise<boolean> => {
  const response:Response<boolean> = await request(`${API_URLS.MENU_BASE}`, {
    method: isAdd ? 'POST' : 'PUT',
    body: JSON.stringify(params)
  })

  if (response.code === 200) {
    ElMessage.success(isAdd ? '添加成功' : '编辑成功')
    return true
  } else {
    return false
  }
} 

export const getMenuName = async (id:number): Promise<string> => {

  const response: Response<MenuItem[]> = await request(API_URLS.MENU_TREE, {
    method: 'GET'
  })
  if (response.code === 200) {
    const menuItems = response.data
    for (let index = 0; index < menuItems.length; index++) {
      const element = menuItems[index];
      if (id === element.id) {
        return element.name
      }

      if (element.children) {
        for (let index = 0; index < element.children.length; index++) {
          const child = element.children[index]
          if (id === child.id) {
            return child.name
          }
        }
      }
    }
  }

  return ''
} 

